//
//  Common.swift
//  Loop
//
//  Created by remy on 2021/9/2.
//

import SpriteKit

public extension String {
    var localized: String { NSLocalizedString(self, comment: "") }
    
    func localized(_ comment: String = "") -> String {
        return NSLocalizedString(self, comment: comment)
    }
    
    static func localized(_ key: String, _ comment: String = "") -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

public extension Set {
    func forEachEnumerated(_ body: ((offset: Int, element: Element)) -> Void) {
        enumerated().forEach(body)
    }
}

public extension Dictionary {
    func forEachEnumerated(_ body: ((offset: Int, element: (key: Key, value: Value))) -> Void) {
        enumerated().forEach(body)
    }
}

public extension Array {
    func forEachEnumerated(_ body: ((offset: Int, element: Element)) -> Void) {
        enumerated().forEach(body)
    }
}

public extension Array where Element: Equatable {
    @discardableResult
    mutating func removeAll(item: Element?) -> [Element] {
        guard let item = item else { return self }
        removeAll(where: { $0 == item })
        return self
    }
    
    @discardableResult
    mutating func removeAll(items: [Element]) -> [Element] {
        guard !items.isEmpty else { return self }
        removeAll(where: { items.contains($0) })
        return self
    }
}

public extension ArraySlice {
    func forEachEnumerated(_ body: ((offset: Int, element: Element)) -> Void) {
        enumerated().forEach(body)
    }
}

public extension Int {
    var color: UIColor { UIColor(self) }
}

public extension String {
    func forEachEnumerated(_ body: ((offset: Int, element: Element)) -> Void) {
        enumerated().forEach(body)
    }
    
    var color: UIColor { UIColor(self) }
    
    var url: URL? { URL(string: self) }
    
    var fileURL: URL { URL(fileURLWithPath: self, isDirectory: false) }
    
    var dirURL: URL { URL(fileURLWithPath: self, isDirectory: true) }
}

public extension UserDefaults {
    subscript(key: String) -> Any? {
        get { return object(forKey: key) }
        set { set(newValue, forKey: key) }
    }
    
    subscript<T>(key: UDSharedKey<T>) -> T? {
        get { return object(forKey: key.rawValue) as? T }
        set { set(newValue, forKey: key.rawValue) }
    }
    
    static func synchronize() {
        UserDefaults.standard.synchronize()
    }
}

public let UDShared = UserDefaults.standard

public class UDSharedKeys: RawRepresentable {
    public typealias RawValue = String
    public var rawValue: String

    public required init(rawValue: String) {
        self.rawValue = rawValue
    }

    public convenience init(_ rawValue: String) {
        self.init(rawValue: rawValue)
    }
}

public final class UDSharedKey<T>: UDSharedKeys {}
